from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import redis_store
from info.models import User, News,Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template


@index_blu.route("/")
@user_login_data
def index():
    # redis_store.set("name","我是无敌的")
#如果用户已经登陆，讲登陆用户的数据传到末班中，供末班使用
    user=g.user

# 右侧的点击排行的实现
    news_list=[]
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
        # news_list是满足条件的6条数据模型，不是简单的列表（
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li=[]
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
        # to_basic_dict()shi model里面写的函数（字典类型），包含news的相关属性

    categories= Category.query.all()
    categories_li=[]
    for category in categories:
        categories_li.append(category.to_dict())

    data={
        "user":user.to_dict() if user else None,
        "news_dict_li":news_dict_li,
        "categories_li":categories_li
    }
    # 如果user有值，就去userd to_dict,如果user没有值，就走esle ，结果为none

    return render_template("news/index.html",data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")

@index_blu.route("/news_list")
def news_list():
    # 1.参数的获取
    cid=request.args.get("cid",1)
    page=request.args.get("page",1)
    per_page=request.args.get("per_page",10)

    # 2,校验参数
    try:
        page=int(page)
        cid=int(cid)
        per_page=int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 3.查询数据
    filters=[]
    #  cid==1时，是默认的首页,按照时间最新排序，没有分类
    if cid!=1:
        filters.append(News.category_id==cid)
    try:
        paginate=News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="数据查询错误")
    # 取到当前页的数据
    # filter()条件过滤
    # paginate.page
    # paginate.per_page
    # paginate.items
    #取当前页面的数据
    news_model_list=paginate.items
    total_page=paginate.pages
    current_page=paginate.page

    news_dict_li=[]
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    data={
        "news_dict_li":news_dict_li,
        "total_page":total_page,
        "current_page":current_page,
    }

    return jsonify(errno=RET.OK,errmsg="ok",data=data)